/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 *
 * \file
 * \brief TaskCtrl interface example 
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 ******************************************************************************
 * NOTE: The following 'Module Info' should be kept up-to-date. Do NOT
 * change its format, insert your information according to the template.
 ******************************************************************************
 * Module Info:
 *
 * Uses drivers:
 *
 * Provides Interfaces:
 * - TaskCtrl
 *
 * Needs Interfaces:
 *
 * General information:
 * 
 ******************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "settings.hpp"
#include "binbag.h"
#include "TaskCtrlServer.hpp"
//*****************************************************************************

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to ODINFO
static int verbose = ODINFO;
//*****************************************************************************

// Choose your namespace
using namespace MaCI;
using namespace MaCI::TaskCtrl;
//*****************************************************************************

// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static std::string gimnetName;
static std::string macigroup = "Dummy";
static std::string maciinstance = "Dummy";
// Configuration parameters
static std::string configurationFile;
//*****************************************************************************


//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(ODSTATUS,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(ODSTATUS,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************


/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tTaskCtrl_Dummy [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  fprintf(stderr,"  [-I name]\t\t\tSpecify the Instance name for this module\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int ExecuteModule(gimi::GIMI &g)
{
  // Construct an MaCICtrlServer instance
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);
  mcs.SetGroupName(macigroup);

  // Construct instance of TaskCtrlServer
  CTaskCtrlServer ds(&mcs, 0, "TaskCtrl serviizi", "TaskCtrl_Dummy");
  ds.SetInterfaceInstanceName(maciinstance);
  // Construct instance of TaskCtrlData && Init to use internal BinBag
  CTaskCtrlData dd;
  SMessageSource ms;
  CTaskCtrlData dataOut;
  EMaCIError e;
  dataOut.CreateInternalBinBag();
  dd.CreateInternalBinBag();

  bool taskCtrlRunning = true;
  unsigned int newTableTaskID = 1;
  std::map<TTaskCtrlTaskID, std::string,TTaskCtrlClassCompareTypeIDs> library;
  //std::map<TTaskCtrlTaskID, std::string,TTaskCtrlClassCompare> table;
  std::map<unsigned int, std::pair<TTaskCtrlTaskID,std::string> > table;

  //  std::map<TTaskCtrlTaskID, TTaskCtrlTaskState,TTaskCtrlClassCompare> taskStates;
  std::map<unsigned int, TTaskCtrlTaskState> taskStates;



  std::map<TTaskCtrlTaskID, std::string,TTaskCtrlClassCompareTypeIDs>::iterator libIterator;
  //std::map<TTaskCtrlTaskID, std::string,TTaskCtrlClassCompare>::iterator tableIterator;
  std::map<unsigned int, std::pair<TTaskCtrlTaskID,std::string> >::iterator tableIterator;

  //  std::map<TTaskCtrlTaskID, TTaskCtrlTaskState,TTaskCtrlClassCompare>::iterator stateIterator;
  std::map<unsigned int, TTaskCtrlTaskState>::iterator stateIterator;

  
  if (ds.Open() == KMaCIOK) {
    // Run!

    while(run) {
      
      e = ds.WaitCommand(dd, ms, 1000);
      dataOut.Reset();
      if (e == KMaCIOK) {
        const TCommand *c = dd.GetCommand();
        TCommand replyCmd;
        replyCmd.cmd = c->cmd;
        replyCmd.flags = KCommandFlagReply;
        replyCmd.taskID = c->taskID;
        replyCmd.cmd = c->commandID;
        bool send_reply = false;
        if (c) {
          dPrint(2,"Got command: %d, data %d, %s,", c->cmd, c->flags,c->taskID.GetString().c_str(),c->commandID);
          
          switch (c->cmd) {                
            
          case KCommandAddTask: {
            bool sendEvent = false; //Send event if the state of a task change

            //Adds task to table and to library(if not there)
            dPrint(1,"*************************************************************");
            dPrint(1,"GOT COMMAND: ADD TASK TO TABLE");
            if(taskCtrlRunning){
              TTaskCtrlTaskID taskID = c->taskID;
              dPrint(1,"%s",
                     taskID.GetString().c_str());
              
              
              std::string x = dd.GetTaskCtrlXMLString();
              dPrint(1,"XML CONTAINS:\n%s",x.c_str());
              //Assign unique taskID
              dPrint(1,"Assigning unique id %u",newTableTaskID);
              
              taskID.taskID = newTableTaskID;
              replyCmd.taskID = taskID;
              newTableTaskID++;
                
              //Adding task to table, send an event...
              table[taskID.taskID] = make_pair (taskID,x);
              sendEvent = true;
              //Send reply, ID already added to replyCmd, so not need to do it
              send_reply = true;
              //Assign

              

              libIterator = library.find(taskID);
            
              if(libIterator == library.end()){
                dPrint(1,"No such task in library, Adding there also");
                library[taskID] = x;
              }


              int ETC = 1000; //< estimate time to complete
              float percentComplete = 0.2;
              taskStates[taskID.taskID] = TTaskCtrlTaskState(taskID, KTaskStateInit,ETC,percentComplete);
              
              dPrint(1,"After adding, table contains %u tasks, and library %d tasks",
                     table.size(),
                     library.size());


              if(sendEvent){
                dPrint(1,"Sending an event!");
                CTaskCtrlData eventData;
                eventData.CreateInternalBinBag();
                // Set timestamp to current (default constructor of Common::TTimestamp)
                eventData.SetTimestamp(Common::TTimestamp());
                //Add a status event
                eventData.SetTaskCtrlStatusEvent(TTaskCtrlStatusEvent(c->taskID, KTaskStateInit, ETC,percentComplete));
                //Send event!
                ds.SendTaskCtrlStatusEvent(eventData);
      
              }
                
            }else{
              dPrint(1,"TaskCtrl not running..Not adding task to table");
            } 
            dPrint(1,"*************************************************************");
            break;
          }
          case KCommandRemoveTask: {
            dPrint(1,"*************************************************************");
              dPrint(1,"GOT COMMAND: REMOVE TASK FROM TABLE");
            if(taskCtrlRunning){
              bool sendEvent =false;
              dPrint(1,"%d",
                     c->taskID.taskID);
              unsigned int taskIDtoRemove = c->taskID.taskID;
              tableIterator = table.find(taskIDtoRemove);
              if(tableIterator != table.end()){
                dPrint(1,"TASK FOUND... Removing...");
                table.erase(tableIterator);
                sendEvent = true;
              }else{
                dPrint(1,"No such task found");
              }

              stateIterator = taskStates.find(taskIDtoRemove);

              if(stateIterator != taskStates.end()){
                
                taskStates.erase(stateIterator);
              }
              dPrint(1,"After removing, table contains %u tasks",
                     table.size());

              ///SEND REMOVED EVENT
              if(sendEvent){
                dPrint(1,"Sending an event!");
                CTaskCtrlData eventData;
                eventData.CreateInternalBinBag();
                // Set timestamp to current (default constructor of Common::TTimestamp)
                eventData.SetTimestamp(Common::TTimestamp());
                //Add a status event
                int ETC = 1000; //< estimate time to complete
                float percentComplete = 0.2;
                eventData.SetTaskCtrlStatusEvent(TTaskCtrlStatusEvent(c->taskID, KTaskStateRemoved, ETC,percentComplete));
                //Send event!
                ds.SendTaskCtrlStatusEvent(eventData);
              }
            }else{
              dPrint(1,"TaskCtrl not running..");
            } 
              dPrint(1,"*************************************************************");
            break;
          }
            
          case KCommandSetTaskState: {
            dPrint(1,"*************************************************************");
            dPrint(1,"GOT COMMAND: Set Task state  (task ID %d)",
                   c->taskID.taskID);
            if(taskCtrlRunning){
              stateIterator = taskStates.find(c->taskID.taskID);
              
              if(stateIterator != taskStates.end() && dd.GetTaskCtrlStateCommand()){
                ETaskCtrlTaskState oldState = taskStates[c->taskID.taskID].taskState;
                ETaskCtrlTaskState newState;
                switch(dd.GetTaskCtrlStateCommand()->cmd){
                case KTaskStateCommandInit:
                  dPrint(1,"Setting task to init state");
                  newState = KTaskStateInit;
                  break;
                
                case KTaskStateCommandStart:
                  dPrint(1,"Setting start. Set task to runnig state");
                  newState = KTaskStateRunning;
                  break;
                case KTaskStateCommandStop:
                  dPrint(1,"Setting task to stop state");
                  newState = KTaskStateStop;
                  break;
                case KTaskStateCommandPause:
                  dPrint(1,"Set task to pause state");
                  newState = KTaskStatePause;
                  break;
                case KTaskStateCommandContinue:
                  dPrint(1,"Continue. Set task to running state");
                  newState = KTaskStateRunning;
                  break;
                default:
                  dPrint(1,"Didn't recognize the wanted command. Setting task to stop");
                  newState = KTaskStateStop;
                  break;

                }
                if(oldState != newState){
                  taskStates[c->taskID.taskID].taskState =  newState;
                  dPrint(1,"Setting task state .");
                  //Send event...
                  CTaskCtrlData eventData;
                  eventData.CreateInternalBinBag();
                  // Set timestamp to current (default constructor of Common::TTimestamp)
                  eventData.SetTimestamp(Common::TTimestamp());
                  //Add a status event
                  eventData.SetTaskCtrlStatusEvent(TTaskCtrlStatusEvent(taskStates[c->taskID.taskID]));
                  //Send event!
                  ds.SendTaskCtrlStatusEvent(eventData);
                }else{
                  dPrint(1,"Wanting the same state... Ignoring.");
                }
      
      
              }else{
                if(stateIterator == taskStates.end()){
                  dPrint(1,"Such task not available...");
                }else{
                  dPrint(1,"no taskctrltaskstate element...");
                }
              }

             
            }else{
              dPrint(1,"TaskCtrl not running..");
            } 
            dPrint(1,"*************************************************************");

            break;
          }


          case KCommandGetTaskState: {

            dPrint(1,"*************************************************************");
            dPrint(1,"GOT COMMAND: Get Task state. %s ",
                   c->taskID.GetString().c_str());
            if(taskCtrlRunning){
              stateIterator = taskStates.find(c->taskID.taskID);
              if(stateIterator != taskStates.end()){
                dPrint(1,"Replying");

                                            
                dataOut.SetTaskCtrlTaskState(stateIterator->second);

              }else{
                dPrint(1,"no such task in table");
              }
            }else{
              dPrint(1,"TaskCtrl not running..");
            } 
            dPrint(1,"*************************************************************");
            send_reply = true;
            break;
          } 

        
          case KCommandGetTaskLibrary: {
            dPrint(1,"*************************************************************");
            dPrint(1,"GOT COMMAND: Get task library");
            if(taskCtrlRunning){
              dPrint(1,"Replying %u tasks",library.size())

              for(EACH_IN_i(library)){
                
                dataOut.AddTaskCtrlXMLString(i->second);
                dataOut.SetTaskCtrlTaskState(TTaskCtrlTaskState(i->first,
                                                                KTaskStateUnknown,
                                                                0,
                                                                0.0));
                

              }
              send_reply = true;  
            }else{
              dPrint(1,"TaskCtrl not running..");
            } 
            dPrint(1,"*************************************************************");
            
            break;
          }
       
        
 

        
          case KCommandGetTasks: {
            //TABLE TASKS
            dPrint(1,"*************************************************************");
            dPrint(1,"GOT COMMAND: Get Tasks(table):");
            if(taskCtrlRunning){
              dPrint(1,"Replying");

              for(EACH_IN_i(table)){
                
                dataOut.AddTaskCtrlXMLString(i->second.second);
                stateIterator = taskStates.find(i->first);
                dataOut.SetTaskCtrlTaskState(stateIterator->second);
                send_reply = true;
              }
            }else{
              dPrint(1,"TaskCtrl not running..");
            } 
            dPrint(1,"*************************************************************");
            
            break;
          }
            
          case KCommandStartTaskCtrl: {
            dPrint(1,"*************************************************************");
            dPrint(1,"Got Command :Start Task Ctrl..");

            if(taskCtrlRunning){
              dPrint(1,"TaskCtrl already running.");
            }else{
              dPrint(1,"Set TaskCtrl to run");
              taskCtrlRunning = true;
            }
            dPrint(1,"*************************************************************");
            break;
          }
          case KCommandStopTaskCtrl: {
            dPrint(1,"*************************************************************");
            dPrint(1,"Got Command :Stop Task Ctrl..");
            
            if(taskCtrlRunning){
              dPrint(1,"Stopped TaskCtrl.");
              taskCtrlRunning = true;
            }else{
              dPrint(1,"Task Ctrl already stopped");
             
            }
            taskCtrlRunning = false;
            dPrint(1,"*************************************************************");
            break;
          }
          case KCommandPauseTaskCtrl: {
            dPrint(1,"*************************************************************");
            dPrint(1,"Got Command :Pause Task Ctrl..");
            
            if(taskCtrlRunning){
              dPrint(1,"Set task ctrl to pause");
              taskCtrlRunning = false;
            }else{
              dPrint(1,"TaskCtrl already Stopped/paused");
            }
            
            dPrint(1,"*************************************************************");
            break;
          }
          case KCommandAddTaskToLibrary: {
            dPrint(1,"*************************************************************");
            dPrint(1,"GOT COMMAND: Add Task To library");
            if(taskCtrlRunning){
              TTaskCtrlTaskID taskID = c->taskID;
              dPrint(1,"%s",
                     taskID.GetString().c_str());

              libIterator = library.find(c->taskID);
              std::string x = dd.GetTaskCtrlXMLString();
              
              dPrint(1,"XML CONTAINS:\n%s",x.c_str());
              if(libIterator == library.end()){


                library[taskID] = x;
                dPrint(1,"Added to library");
                dPrint(1,"After adding, library contains %d tasks",
                       library.size())

                dPrint(1,"*************************************************************");
              }else{
                dPrint(1,"Task already added to library with the same ID. Sending an error message");
                replyCmd.flags = KCommandFlagReplyCmdError;
                std::string error = "There is a task with the same type numbers";
                dataOut.AddErrorString(error);
                
              }
              send_reply = true;
              
              dPrint(1,"*************************************************************");
              
            
              
            }else{
              dPrint(1,"TaskCtrl not running..");
            } 
            break;
          }
          case KCommandRemoveTaskFromLibrary: {
            dPrint(1,"*************************************************************");
            dPrint(1,"GOT COMMAND: REMOVE TASK FROM LIBRARY");
            if(taskCtrlRunning){
              dPrint(1,"%s",c->taskID.GetString().c_str());
              
              libIterator = library.find(c->taskID);
              if(libIterator != library.end()){
                  
                dPrint(1,"Task found, removing");
                library.erase(libIterator);
              }else{
                dPrint(1,"No such task found :(");
              }
              
            }else{
              dPrint(1,"TaskCtrl not running..");
            } 
            break;
            dPrint(1,"*************************************************************");
          }

          default: {
            dPrint(1,"Got command crap. You suck! Sending up yours message.");
            replyCmd.flags = KCommandFlagNotSupported;  

            break;
          }            
          }
          // Add a call to gimi:stop()
        
          if(send_reply){
            dataOut.SetCommand(replyCmd);
            dd.Print(1);
            dPrint(100,"Printing generated outgoing container.");
            dataOut.Print(100);
            //send reply to synch. message
            ds.SendReply(dataOut, ms);
            
          }
        }else {
        dPrint(ODERROR,"Got Command, but no Command element present (e = %d)???",e);

        }
      } 
    }

    ds.Close();
    g.stop();
  } else {
    dPrint(ODERROR,"Failed to open CTaskCtrlServer instance! Fatal error.");
    return -1;
    
  }
  
  dPrint(1,"Stopping...");
  dPrint(1,"saas");
  return 0;

}
int main(int argc, char *argv[]) 
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(verbose);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.5 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "f:n:u:p:G:I:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////

    case 'n':
      gimnetName = optarg;
      dPrint(ODVINFO,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(ODVINFO,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(ODVINFO,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(ODVINFO,"Using MaCI-Group '%s'", optarg);
      break;

    case 'I':
      maciinstance = optarg;
      dPrint(ODVINFO,"Using MaCI-Group '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(ODERROR,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(ODINFO,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);

  }
  dPrint(1,"Stopping...");
  return 0;
}
